package com.lune.job.framework.mvc;

import com.lune.job.framework.exception.TokenException;
import com.lune.job.framework.redis.RedisUtil;
import com.lune.job.utils.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * token拦截器
 **/
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //请求中获取token
        String token = request.getHeader("token");
        boolean flag = redisUtil.hasKey(token);
        if (flag){
            UserThreadLocal.set(token); //本地线程设置token
            redisUtil.expire(token,redisUtil.EXPR);
        }else {
            throw new TokenException("超时或者是不合法的token");
        }
        return  true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();   //本地线程清空token
    }
}
